package testDay;

import java.util.logging.Level;

public class day2_3 {
    public int[] twoSum(int[] numbers, int target) {
        /*两层循环超时
        int[] res = new int[2];
        for (int i=0;i<numbers.length-1;i++){
            for (int j = i+1;j<numbers.length;j++){
                if (numbers[i]+numbers[j]==target){
                    res[0] = i;
                    res[1] = j;
                }
            }
        }
        return res;  */
        /*
         * 1.设置双指针left，right，while循环从左右端开始执行
         * 2.因为数组有序且元素为一，比较left+right与target，若和大于target，left++，若和小于target，则right--
         * 若和等于target，记录left，right，退出循环。
         */
        int[] res = new int[2];
        int left = 0;
        int right = numbers.length - 1;
        while (left < right) {
            int temp = numbers[left] + numbers[right];
            if (temp == target) {
                res[0] = left;
                res[1] = right;
                break;
            }
            if (temp < target) {
                left++;
            }
            if (temp > target) {
                right--;
            }
        }
        return res;
    }
}
